package com.small.sentinel.slots.block.authority;

import com.small.common.core.constants.CommonConstants;
import com.small.common.core.util.StringUtil;
import com.small.sentinel.Context;
import com.small.sentinel.slots.block.RuleConstant;

/**
 * 权限规则检查器
 */
public class AuthorityRuleChecker {

    /**
     * 检查是否通过
     * @param rule
     * @param context
     * @return
     */
    static boolean passCheck(AuthorityRule rule, Context context) {
        //限制的权限
        String limitApp = rule.getLimitApp();
        //来源
        String requester = context.getOrigin();
        if (StringUtil.isEmpty(requester) || StringUtil.isEmpty(limitApp)) {
            return true;
        }
        //判断是否包含请求来源
        int pos = limitApp.indexOf(requester);
        boolean contain = pos > -1;
        if (contain){
            boolean exactlyMatch = false;
            String[] appArray = limitApp.split(CommonConstants.COMMAS);
            for (String app : appArray) {
                if (requester.equals(app)) {
                    exactlyMatch = true;
                    break;
                }
            }
            contain = exactlyMatch;
        }

        if (rule.getStrategy() == RuleConstant.AUTHORITY_BLACK && contain){
            return false;
        }
        if (rule.getStrategy() == RuleConstant.AUTHORITY_WHITE && !contain){
            return false;
        }
        return true;
    }
}
